<template>
  <label :for="name" class="select-image-upload" :class="showType" :style="imgsrc && {'background-image': `url(${imgsrc})`}">
    <input type="file" 
      :name="name" 
      :id="name"
      @change="onSelectImageUplaod">
  </label>
</template>

<script>
  export default {
    props: {
      imgsrc: {
        type: String
      },
      type: {
        type: String,
        default: 'default'
      },
      name: {
        type: String
      }
    },
    data() {
      return {
        showType: this.type
      }
    },
    methods: {
      onSelectImageUplaod(ev) {
        const el = ev.target
        if (!el.value) {
          el.parentNode.style.backgroundImage = ''
          this.showType = 'default'
        } else {
          this._selectImageUpload(el)
        }
      },
      _selectImageUpload(el) {
        if (el.value && !/.jpg|.jepg|.png/i.test(el.value)) {
          this.$toast('图片格式无效，请重新选择')
          return false
        }
        if (el.files && el.files[0]) {
          el.parentNode.style.backgroundImage = 'url(' + window.URL.createObjectURL(el.files[0]) + ')'
          this.showType = ''
        } else {
          // IE下，使用滤镜
          el.select()
          window.parent.document.body.focus()
          const imgSrc = document.selection.createRange().text
          el.parentNode.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)'
          el.parentNode.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgSrc
          document.selection.empty()
        }
        return true
      }
    }
  }
</script>

<style lang="scss" scoped>
  .select-image-upload {
    display: block;
    width: 100%;
    height: 180px;
    border-radius: 4px;
    background-color: #fafafa;
    border: 2px dashed #e6e6e6;
    background-size: 100% 100%;
    cursor: pointer;
    &.default {
      background-size: 44% 60%;
      background-repeat: no-repeat;
      background-position: center center;
      background-image: url();
    }
    &.noimage {
      background-size: 60% 20%;
      background-repeat: no-repeat;
      background-position: center center;
      background-image: url();
    }
    input {
      width: 0;
      height: 0;
      opacity: 0;
    }
  }
</style>
